package com.cqwshzj.thread.worker;/**
 * @Description:
 * @Auther: Huang Zhijin
 * @Version: 1.0.0
 * @Date: 2021/4/12 10:41
 */

import com.cqwshzj.common.JobConstant;
import com.cqwshzj.thread.bean.Stateable;
import org.apache.commons.lang3.RandomUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 *
 * 〈〉
 *
 * @author Huang Zhijin
 * @create 2021/4/12
 * @since 1.0.0
 */
public class AssistantBizWorker<T extends Stateable> implements Runnable {

	private static final Logger log = LoggerFactory.getLogger( AssistantBizWorker.class );

	//---------------------------------------

	private List<T> downloadList ;
	private LinkedBlockingQueue<T> checkQueue;

	private CountDownLatch filesCountSignal;
	private CountDownLatch assistantThreadSignal;

	//---------------------------------------
	/** 业务数统计 */
	private int bizCount = 0;

	//---------------------------------------

	public AssistantBizWorker(List<T> downloadList,
							  LinkedBlockingQueue<T> checkQueue,
							  CountDownLatch filesCountSignal,
							  CountDownLatch assistantThreadSignal) {
		this.downloadList = downloadList;
		this.checkQueue = checkQueue;
		this.filesCountSignal = filesCountSignal;
		this.assistantThreadSignal = assistantThreadSignal;
	}

	//---------------------------------------

	@Override
	public void run() {
		log.info("--------  assistant biz worker end   --------");

		try {
			long start = System.currentTimeMillis();

			int downloadFiles = 0;
			if(CollectionUtils.isEmpty( downloadList )){
				downloadFiles = downloadList.size();
				for (int i = 0; i < downloadFiles; i++) {

					downloadFile( downloadList.get(i) );
					//每下载一个文件 减一
					filesCountSignal.countDown();
				}
			}
			log.info(" download over, thread=[{}], downloadFiles=[{}], cost=[\t{}]ms. ", filesCountSignal.getCount(), downloadFiles, (System.currentTimeMillis()-start) );

		}catch (Exception e){
			log.error(e.getMessage(),e);
		}
		assistantThreadSignal.countDown();
		log.info("--------  assistant biz worker end   --------");

	}



	private void downloadFile(T subject) {
		bizCount++;
		log.info(" download subject . id=[{}] state=[{}] .", subject.getIdentityField(), subject.getState());
		try {
			final int timeout = RandomUtils.nextInt(1, 5);
			if (timeout > 1 ){
				subject.setState( JobConstant.COMMON_YES );
			}else{
				subject.setState( JobConstant.COMMON_NO );
			}
			TimeUnit.MILLISECONDS.sleep(timeout);

			checkQueue.offer( subject );
			return;
		} catch (Exception e) {
			log.error(e.getMessage(),e);
		}
	}
}
